<?php

namespace CHOMP\SGIBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CHOMP\SGIBundle\Entity\Timesheet;
use CHOMP\SGIBundle\Form\TimesheetType;
use Symfony\Component\HttpFoundation\Response;
use CHOMP\SGIBundle\Entity\Rol;
use CHOMP\SGIBundle\Services\SessionManager;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Session\Session;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;



/**
 * Timesheet controller.
 *
 * @Route("/timesheet")
 */
class TimesheetController extends Controller
{
	/**
	 * 
	 * @var SessionManager
	 * @DI\Inject("session.manager")
	 */
	public $sessionSvc;

    /**
     * Lists all Timesheet entities.
     *
     * @Route("/", name="timesheet")
     * @Method("GET")
     * @Template()
     */
    public function listarAction($page, $incidente)
    {		
		if ($this->sessionSvc->userIsLogged()){
			$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Timesheet')->getAllByIncidente($incidente);		
	
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:Timesheet:listar.html.twig', array('timesheets' => $paginador, 'idIncidente' => $incidente));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }
	
    /**
     * Creates a new Timesheet entity.
     *
     * @Route("/{idIncidente}", name="timesheet_create")
     * @Method("POST")
     * @Template("CHOMPSGIBundle:Timesheet:nuevo.html.twig")
     */
    public function createAction(Request $request, $idIncidente)
    {
        $entity = new Timesheet();

		$incidente = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Incidente')->find($idIncidente);
		$entity->setIncidente($incidente);
		$entity->setCuentaAnalitica($incidente->getCuentaAnalitica());
		
		$usuario = $this->sessionSvc->getCurrentUser();
		$entity->setUsuario($usuario);
        
		$form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
			
            return $this->redirect($this->generateUrl('timesheet_listar', array('page' => 1, 'incidente' => $idIncidente)));
        }
		
        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
			'idIncidente' => $idIncidente
        );
    }

    /**
    * Creates a form to create a Timesheet entity.
    *
    * @param Timesheet $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Timesheet $entity)
    {
		$idInc = $entity->getIncidente()->getId();
        $form = $this->createForm(new TimesheetType(), $entity, array(
            'action' => $this->generateUrl('timesheet_create', array('idIncidente' => $idInc)),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }

    /**
     * Displays a form to create a new Timesheet entity.
     *
     * @Route("/nuevo/{idIncidente}", name="timesheet_nuevo")
     * @Method("GET")
     * @Template()
     */
    public function nuevoAction($idIncidente)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$entity = new Timesheet();
			$incidente = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Incidente')->find($idIncidente);
			$entity->setIncidente($incidente);
			$entity->setCuentaAnalitica($incidente->getCuentaAnalitica());
	
			$usuario = $this->sessionSvc->getCurrentUser();
			$entity->setUsuario($usuario);
			
			$form = $this->createCreateForm($entity);
	
			return array(
				'entity' => $entity,
				'form'   => $form->createView(),
				'idIncidente' => $incidente->getId()
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
     * Finds and displays a Timesheet entity.
     *
     * @Route("/{id}", name="timesheet_ver")
     * @Method("GET")
     * @Template()
     */
    public function verAction($id)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Timesheet')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Timesheet entity.');
			}
		   return array(
				'entity'      => $entity,
				'delete_form' => $deleteForm->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
     * Displays a form to edit an existing Timesheet entity.
     *
     * @Route("/{id}/edit", name="timesheet_editar")
     * @Method("GET")
     * @Template()
     */
    public function editarAction($id)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Timesheet')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Timesheet entity.');
			}
	
			$editForm = $this->createEditForm($entity);
			
			return array(
				'entity'      => $entity,
				'edit_form'   => $editForm->createView(),
				'idIncidente' => $entity->getIncidente()->getId()
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
    * Creates a form to edit a Timesheet entity.
    *
    * @param Timesheet $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Timesheet $entity)
    {
        $form = $this->createForm(new TimesheetType(), $entity, array(
            'action' => $this->generateUrl('timesheet_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }
    /**
     * Edits an existing Timesheet entity.
     *
     * @Route("/{id}", name="timesheet_update")
     * @Method("PUT")
     * @Template("CHOMPSGIBundle:Timesheet:editar.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CHOMPSGIBundle:Timesheet')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Timesheet entity.');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('timesheet_listar', array('page' => 1, 'incidente' => $entity->getIncidente()->getId())));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
			'idIncidente' => $entity->getIncidente()->getId()
        );
    }
}
